package com.lizk.rocketmq.orderly;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import com.lizk.rocketmq.Config;

public class ProducerOrderly {
	public static void main(String[] args) {
		
		DefaultMQProducer producer = new DefaultMQProducer("PRODUCER_GROUP_ORDER");
		producer.setNamesrvAddr(Config.NAMESRV_ADDR);
		
		try {
			producer.start();

			for(int i = 1 ; i < 9 ; i++){
				Message msg = new Message("topic_order","order",UUID.randomUUID().toString(),("我是消息的内容"+i).getBytes(Config.ENCODE_UTF8));
				SendResult sr = producer.send(msg, new MessageQueueSelector(){
					@Override
					public MessageQueue select(List<MessageQueue> paramList, Message paramMessage, Object paramObject) {
						int id = (int)paramObject;
						
						int qIndex = id % paramList.size();
						
						return paramList.get(qIndex);
					}
					
				},i);
				System.out.println(sr);
			}
			
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MQClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemotingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MQBrokerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			producer.shutdown();
		}
		
	}
}
